<template>
    <div>
        count = {{ props.count }}
        <br />
        msg = {{ props.msg }}
        <hr />

        鼠标位置：x={{ x }},y={{ y }}
        <div>
            doubleCount = {{ doubleCount }}
            <button @click="setCount">change count {{ count }}</button>
        </div>

        <div>
            <button @click="setState">{{ state.msg }}</button>
        </div>

        <h1 ref="h1Ref">我是dom标签h1</h1>
    </div>
</template>
<script setup lang="ts">
import {
    ref,
    reactive,
    computed,
    watch,
    inject,
    onMounted,
    onUnmounted
} from 'vue';
//子组件内部通过 defineProps宏 接受传递的数据
const props = defineProps({
    count: Number,
    msg: String
});

// 响应式状态
const count = ref(0);
const x = ref(0);
const y = ref(0);
const h1Ref = ref(null);

// 用来修改状态、触发更新的函数
function update(event) {
    x.value = event.pageX;
    y.value = event.pageY;
}

function setCount() {
    count.value++;
}

//计算属性
const doubleCount = computed(() => count.value * 2);

// reactive返回一个响应式对象
const state = reactive({ msg: 'hello world' });

//修改响应式对象，更新视图
const setState = () => {
    if (count.value % 2 === 0) {
        state.msg = '你好世界！';
    } else {
        state.msg = 'hello world!';
    }
};

//watch侦听变化
watch(count, (newValue, oldValue) => {
    console.log(`count发生了变化，老值为${oldValue},新值为：${newValue}`);
});

//watch侦听多个响应式变量
watch([count, state], ([newCount, newState], [oldCount, oldState]) => {
    console.log(
        `count或者state变化了，`,
        [newCount, newState.msg],
        [oldCount, oldState.msg]
    );
});

// 底层组件通过 inject 函数提供数据
const tdata = inject('tableData');

// 生命周期钩子
onMounted(() => {
    h1Ref.value.style.backgroundColor = 'red';
    console.log('h1 DOM对象', h1Ref.value);

    console.log('顶层组件的注入变量tableData', tdata);

    window.addEventListener('mousemove', update);
});
onUnmounted(() => {
    window.removeEventListener('mousemove', update);
});
</script>